# This file is part of the Net::Tube module.
#
# Net::Tube is Free Software; you can use, redistribute it and/or
# modify it under the terms of either:
#
# a) the GNU General Public License as published by the Free Software
#    Foundation, either version 2, or (at your opinion) any later
#    version, or
#
# b) the "Artistic License" which comes with Perl.
#
use strict;
use warnings;
use Test::Simple tests => 2;


use Net::Tube;
use Net::Tube::Loader::File;
use Net::Tube::Filter::SemanticMerge;

use XML::LibXML;


sub test_new {
    my $x = Net::Tube::Filter::SemanticMerge->new();
    unless ( defined $x && ref $x ) {
        print "#object not created \n";
        return 0;
    }
    unless ( $x->isa("Net::Tube::Filter::SemanticMerge") ) {
        print "# wrong object type created\n";
        return 0;
    }
    return 1;
}

ok( test_new(), "test new" );

sub test_merge {
    my $m = Net::Tube::Machine->new();
    my $c =
      Net::Tube::Loader::File->new(
     { loadSource => [ 'tdata/test_feed_atom_simple1.xml', 'tdata/test_feed_atom_simple2.xml' ] } );
    my $sm = Net::Tube::Filter::SemanticMerge->new;
    my $atomns = "http://www.w3.org/2005/Atom";
    $sm->set_config_entry('mergeElements', "//*[local-name() = 'entry']");

    my $data;
    eval { $data = $m->execute( [ $c, $sm ] ); };
    
    if ($@) {
        print "# and error occored: $@\n";
        return 0;
    }
    
    my $p = XML::LibXML->new();
    my $td = $p->parse_string($data);
    my @nodes = $td->findnodes("//*[namespace-uri() = '$atomns' and local-name() = 'entry']");
        
    unless ( scalar @nodes == 2 ) {
        print "# data not correctly merged, got wrong number of nodes " . scalar(@nodes);
        print "\n";
        return 0;
    }
    
    @nodes = $td->findnodes("//*[namespace-uri() = '$atomns' and local-name() = 'entry']/*[namespace-uri() = '$atomns' and local-name() = 'title']");
    
    unless (scalar @nodes == 2) {
        print "# data not correctly merged, got wrong number of nodes for the title " . scalar(@nodes);
        print "\n";
        return 0;
    }
    
    unless ($nodes[0]->textContent eq 'dotSUB: Multilinguale Untertitelung von Videoinhalten') {
        print "# received a wrong title at the first node got '" . $nodes[0]->textContent. "'";
        print "\n";
        return 0;
    }
    
    unless ($nodes[1]->textContent eq 'Educating People') {
        print "# received a wrong title at the second node got " . $nodes[1]->textContent;
        print "\n";
        return 0;
    }
    return 1;
}

ok( test_merge(), "merge" );

